package com.zzyl.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.Constants;
import com.zzyl.dto.WechatUserLoginDTO;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.WechatThirdPartyService;
import com.zzyl.service.WechatUserLoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.GetWechatOpenIdVO;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class WechatUserLoginServiceImpl implements WechatUserLoginService {

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;
    @Value("${zzyl.framework.jwt.ttl}")
    private int expireTime;

    @Resource
    MemberMapper memberMapper;

    @Resource
    WechatThirdPartyService wechatThirdPartyService;



    @Override
    public ResponseResult<LoginVo> login(WechatUserLoginDTO dto) {
        //1. 调用对三方微信接口获取信息
        //获取微信用户唯一openid
        GetWechatOpenIdVO openId = wechatThirdPartyService.getOpenId(dto.getCode());
        //获取手机号
        String phoneNumber = wechatThirdPartyService.getPhoneNumber(dto.getPhoneCode());
        //2.对member表进行新增或者修改
        //判断该微信用户是否已经注册
        Member member = memberMapper.queryByOpenId(openId.getOpenid());
        if (Objects.isNull(member)) {
            //新增
            member = new Member();
            member.setOpenId(openId.getOpenid());
            member.setPhone(phoneNumber);
            //随机组装昵称，词组+手机号后四位
            String nickNamePrefix = RandomUtil.randomEle(List.of("曼波~~","小蓝","小绿","小黄"), 1);
            String phoneSuffix = StrUtil.sub(phoneNumber, 7, 11);
            member.setName(nickNamePrefix + phoneSuffix);
            int insert = memberMapper.insert(member);
            log.info("插入新微信小程序用户{}",insert);
        }else {
            //更新
            if (!member.getPhone().equals(phoneNumber)) {
                member.setPhone(phoneNumber);
                memberMapper.update(member);
            }
        }
        //3.生成 jwt Token
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID,member.getId());
        claims.put(Constants.JWT_USERNAME,member.getName());
        String token = JwtUtil.createJWT(secretKey, expireTime, claims);
        loginVo.setToken(token);
        return ResponseResult.success(loginVo);
    }
}
